<template>
  <!-- 窗口内容 -->
  <a-modal
    :open="props.modelVisible"
    title="新建分配"
    ok-text="确认"
    cancel-text="取消"
    @ok="onOk"
    @cancel="
      formRef.resetFields();
      emit('update:modelVisible', false);
    "
    :maskClosable="true"
  >
    <!-- 表单内容 -->
    <a-form
      ref="formRef"
      :model="formState"
      name="form_in_modal"
      :label-col="{ style: { width: '90px' } }"
      AutoComplete="off"
    >
      <a-form-item
        name="classId"
        label="选择班级"
        :rules="[{ required: true, message: '班级不能为空', trigger: 'blur' }]"
      >
        <a-select
          v-model:value="formState.classId"
          placeholder="请选择班级"
          :field-names="{ label: 'className', value: 'classId' }"
          :options="classes"
          @change="selectClass"
          :listHeight="150"
        />
      </a-form-item>
      <a-form-item
        name="teamId"
        label="选择小组"
        :rules="[{ required: true, message: '小组不能为空', trigger: 'blur' }]"
      >
        <a-select
          v-model:value="formState.teamId"
          placeholder="请选择承担小组"
          :field-names="{ label: 'teamName', value: 'teamId' }"
          :options="teams"
          @change="changeMembers(formState.teamId)"
          :listHeight="150"
        />
      </a-form-item>
      <!-- <a-form-item name="userList" label="承担对象">
        <a-select
          v-model:value="formState.userList"
          mode="multiple"
          placeholder="请选择承担对象"
          :showSearch="true"
          optionFilterProp="userName"
          :field-names="{ label: 'userName', value: 'userId' }"
          :options="items"
          :listHeight="150"
        >
        </a-select>
      </a-form-item> -->
      <a-form-item
        name="endTime"
        label="截至时间"
        :rules="[{ required: true, message: '截止时间不能为空', trigger: 'blur' }]"
      >
        <a-date-picker v-model:value="formState.endTime" style="width: 100%" show-time />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
import { message } from 'ant-design-vue';
import { reactive, ref, toRaw } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import type { UnwrapRef } from 'vue';
import TaskDao from '@/daos/task_dao';
import ClassDao from '@/daos/class_dao';
import ProjectDao from '@/daos/project_dao';
import { useStore } from 'vuex';
import dayjs from 'dayjs';
const store = useStore();

const projectDao = new ProjectDao();
const taskDao = new TaskDao();
const classDao = new ClassDao();

//接口定义
interface FormState {
  userList: []; //用户列表
  taskId: number; //项目id
  classId: number;
  creatorId: number; //创建者id
  createTime: dayjs.Dayjs; //创建时间
  endTime: dayjs.Dayjs; //截止时间
  teamId: number; //小组id
}

//modelVisible用于开关窗口，默认关闭
const props = defineProps({
  modelVisible: {
    type: Boolean,
    default: false
  },
  //任务ID，用于选择任务
  taskId: {
    type: Number,
    defalt: null
  }
});
//emit用于修改窗口状态
const emit = defineEmits(['update:modelVisible', 'confirm']);
//普通项目成员列表
const items = ref([]);
//班级列表
const classes = ref([]);
//小组列表
const teams = ref([]);
//定义表单
const formRef = ref<FormInstance>();
//根据选中的小组id 获取对应的成员
const changeMembers = (teamId) => {
  const team = teams.value.find((team) => team.teamId === teamId);
  formState.userList = [];
  items.value = team.userList;
};
//初始表单内容全为undefined
const formState: UnwrapRef<FormState> = reactive({
  userList: undefined,
  classId: undefined,
  teamId: undefined,
  taskId: undefined,
  endTime: undefined,
  createTime: undefined,
  creatorId: store.getters.userId
});
//查询项目成员
const findMumber = () => {
  projectDao
    .findProjectTeamsAndMembersByProjectId(null, formState.teamId)
    .then((result) => {
      teams.value = result.data.data;
    })
    .catch((error) => {
      console.error('findTeamsAndMembers 错误', error);
    });
};

//获取班级信息
const findClass = () => {
  return classDao.findClassByCourseId(store.getters.courseId).then((result) => {
    console.log(result);

    classes.value = result.data.data; // 直接替换整个数组
  });
};
//选择班级后获取小组信息
const selectClass = (value) => {
  teams.value = classes.value.find((item) => item.classId == value).teamList;
};
const onOk = () => {
  formRef.value
    .validateFields()
    .then(() => {
      //请求后端
      formState.createTime = dayjs();
      taskDao
        .addAssignmentAndUndertaker(toRaw(formState))
        .then((result) => {
          message.success(result.data.msg);
          //更新任务页面内容
          emit('confirm');
          //更新窗口状态，false为关闭
          emit('update:modelVisible', false);
          //清空表单内容
          formRef.value.resetFields();
        })
        .catch((error) => {
          console.error('创建任务分配失败 addAssignmentAndUndertaker', error);
        });
    })
    .catch((error) => {
      console.log('数据验证失败:', error);
    });
};
watch(
  () => props.modelVisible,
  (newValue) => {
    if (newValue === true) {
      formState.taskId = props.taskId;
      findClass();
      findMumber();
    }
  }
);
</script>
<style scoped></style>
